package model.player;

import model.map.GameTile;
import model.mapping.PlayableMapping;
import model.playable.Playable;
import model.playable.RallyPoint;

public class RallyPointManager implements CyclableManager
{
	private PlayableMapping playableMapping = PlayableMapping.getPlayableMapping();
	private RallyPoint[] rps;
	private int grabPointer;
	private Player player;
	
	public RallyPointManager(Player player)
	{
		rps = new RallyPoint[10];
		grabPointer = 0;
		this.player = player;
		for (int i = 0; i < rps.length; i++)
			addRallyPoint(i, player.getStartingLocation());
	}
	
	public void addRallyPoint(int i, GameTile tile)
	{
		if (rps[i] != null)
			return;
		
		RallyPoint r = new RallyPoint(player);
		
		rps[i] = r;
		
		playableMapping.addRallyPoint(tile, r);
	}
	
	public RallyPoint getRallyPoint(int id)
	{
		return rps[id];
	}
	
	public Playable getCurPlayable() 
	{	
		while (rps[grabPointer] == null)
		{
			grabPointer = (grabPointer +1) % rps.length;
		}
		
		return rps[grabPointer];
	}

	public Playable getNextPlayable() 
	{
		grabPointer = (grabPointer +1) % rps.length;
		
		while (rps[grabPointer] == null)
		{
			grabPointer = (grabPointer +1) % rps.length;
		}
		return rps[grabPointer];
	}

	public Playable getPrevPlayable() 
	{		
		grabPointer = (grabPointer -1 + rps.length) % rps.length;
		
		while (rps[grabPointer] == null)
		{
			grabPointer = (grabPointer -1 + rps.length) % rps.length;
		}
		return rps[grabPointer];
	}
	
	public void remove(int i)
	{
		if (rps[i] != null)
		{
			playableMapping.removeRallyPoint(rps[i]);
			rps[i] = null;
		}
	}

	public boolean isEmpty() 
	{
		for (RallyPoint r : rps)
			if (r != null)
				return false;
		
		return true;
	}



	public boolean isFull()
	{
		for (RallyPoint r : rps)
			if (r == null)
				return false;
		
		return true;
	}
	
	public void update()
	{
		for (RallyPoint r : rps)
			if (r != null)
				r.executeCommand();
		
	}

	@Override
	public Playable getPlayableID(int id) 
	{
		return rps[id];
	}


	@Override
	public String getType() 
	{
		return "Rally Point";
	}
}
